package com.awen.htmlparser.util;

import org.htmlparser.NodeFilter;
import org.htmlparser.filters.*;

/**
 * 由valuePattern生成HTMLPaser的NodeFilter的工具类.
 * User: awen
 * Date: 13-4-8
 * Time: 下午12:00
 * To change this template use File | Settings | File Templates.
 */
public class ValuePatternUtil {

    /**
     * 解析valuePatter为NodeFilter
     *
     * @param pathPattern 格式类似:/html/body.b91/div#bnsLayout/div#888/ul/li   #与.不能同一级path下出现
     * @return
     */
    public static NodeFilter convertPatternTONodeFilter(String pathPattern) {

        NodeFilter nodeFilter = null;
        if(pathPattern.indexOf("!") == 0){
            nodeFilter = pathPattern.contains("#") ? new NotFilter(new HasAttributeFilter("id", pathPattern.substring(2))) : new NotFilter(new HasAttributeFilter("class", pathPattern.substring(2)));
        }else{
            nodeFilter = pathPattern.indexOf("LINKREGEX:") == 0 ?
                    new LinkRegexFilter(pathPattern.split(":")[1]) :
                    (pathPattern.indexOf("REGEX:") == 0 ?
                            new RegexFilter(pathPattern.split(":")[1]) :
                            (pathPattern.contains("#") ?
                                    new AndFilter(new TagNameFilter(pathPattern.split("\\#")[0]),
                                            !(pathPattern.split("\\#")[1].indexOf("!")==0) ? new HasAttributeFilter("id", pathPattern.split("\\#")[1]) : new NotFilter(new HasAttributeFilter("id", pathPattern.split("\\#")[1].substring(1)))) :
                                    (
                                            pathPattern.contains(".") ?
                                                    new AndFilter(new TagNameFilter(pathPattern.split("\\.")[0]),
                                                            !(pathPattern.split("\\.")[1].indexOf("!")==0) ? new HasAttributeFilter("class", pathPattern.split("\\.")[1]) : new NotFilter(new HasAttributeFilter("class", pathPattern.split("\\.")[1].substring(1)))) :
                                                    new TagNameFilter(pathPattern)
                                    )));
        }
        return nodeFilter;
    }
}
